﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Webdiyer.WebControls.Mvc;
using QLPKWeb.Models.LinQ.LichLamViec;
using DONGACS.Common;
using System.Web.Mvc;
using QLPKWeb.Models.FormBean.LichLamViecModel;
using QLPKWeb.Models.LinQ.Common;

namespace QLPKWeb.BussinessDelegate.LichLamViecDelegate
{
    public class LichLamViecDelegate
    {        
        DBLichLamViecDataContext DBLichLamViec = new DBLichLamViecDataContext();
        DBCommonDataContext DBCommon = new DBCommonDataContext();
        LichLamViec_NguoiChuanBiDelegate LichLamViec_NguoiChuanBiDelegate = new LichLamViec_NguoiChuanBiDelegate();
        LichLamViecSharedDelegate LichLamViecSharedDelegate = new LichLamViecSharedDelegate();

        public LichLamViec Insert(LichLamViecForm form)
        {
            try
            {
                LichLamViec objLichLamViec = this.BuildLichLamViecObject(form);
                objLichLamViec.Status = false;
                DBLichLamViec.LichLamViecs.InsertOnSubmit(objLichLamViec);
                DBLichLamViec.SubmitChanges();
                objLichLamViec = this.GetLichLamViecIdMax();
                string[] arrThanhPhan = form.InListIdThanhPhan.Split(',');
                for (int i = 0; i < arrThanhPhan.Length - 1; i++)
                {
                    LichLamViecShared objShare = new LichLamViecShared();
                    objShare.IDLich = objLichLamViec.ID;
                    objShare.IdUser = int.Parse(arrThanhPhan[i].Trim());
                    LichLamViecSharedDelegate.InsertLichLamViec(objShare);
                }
                string[] arrNguoiChuanBi = form.InListIdNguoiChuanBi.Split(',');
                for (int i = 0; i < arrNguoiChuanBi.Length - 1; i++)
                {
                    LichLamViec_NguoiChuanBi objNguoiChuanBi = new LichLamViec_NguoiChuanBi();
                    objNguoiChuanBi.IDLich = objLichLamViec.ID;
                    objNguoiChuanBi.IdUser = int.Parse(arrNguoiChuanBi[i].Trim());
                    LichLamViec_NguoiChuanBiDelegate.InsertLichLamViec(objNguoiChuanBi);
                }
                return objLichLamViec;
            }
            catch (Exception)
            {
                return new LichLamViec();
            }
        }
        CommonDelegate.CommonDelegate CommonDelegate = new CommonDelegate.CommonDelegate();
        public void Update(LichLamViecForm form)
        {
            LichLamViec obj = DBLichLamViec.LichLamViecs.SingleOrDefault(p => p.ID == form.ID);
            obj.DiaDiem = form.DiaDiem;
            obj.DonViChuTri = form.DonViChuTri;
            //obj.EndTime = CommonDelegate.ConverToTime(form.EndTimeHH, form.EndTimeMM);
            //obj.EventDate = CommonDelegate.ConvertToDateTine(form.EventDate);
            obj.StartTime = CommonDelegate.ConvertTime(form.EventDate, form.StartTimeHH + ":" + form.StartTimeMM);
            obj.EndTime = CommonDelegate.ConvertTime(form.EndDate, form.EndTimeHH + ":" + form.EndTimeMM);
            obj.GhiChu = form.GhiChu;
            obj.KhachMoi = form.KhachMoi;
            //obj.NguoiChuanBi = form.NguoiChuanBi;
            obj.NoiDung = form.NoiDung;
            //obj.StartTime = CommonDelegate.ConverToTime(form.StartTimeHH, form.StartTimeMM);
            obj.Status = false;
            obj.ID = form.ID;
            LichLamViecSharedDelegate.DeleteLichLamViecByIdLich(obj.ID);
            string[] arrThanhPhan = form.InListIdThanhPhan.Split(',');
            for (int i = 0; i < arrThanhPhan.Length - 1; i++)
            {
                LichLamViecShared objShare = new LichLamViecShared();
                objShare.IDLich = obj.ID;
                objShare.IdUser = int.Parse(arrThanhPhan[i].Trim());
                LichLamViecSharedDelegate.InsertLichLamViec(objShare);
            }
            LichLamViec_NguoiChuanBiDelegate.DeleteLichLamViecByIdLich(obj.ID);
            string[] arrNguoiChuanBi = form.InListIdNguoiChuanBi.Split(',');
            for (int i = 0; i < arrNguoiChuanBi.Length - 1; i++)
            {
                LichLamViec_NguoiChuanBi objNguoiChuanBi = new LichLamViec_NguoiChuanBi();
                objNguoiChuanBi.IDLich = obj.ID;
                objNguoiChuanBi.IdUser = int.Parse(arrNguoiChuanBi[i].Trim());
                LichLamViec_NguoiChuanBiDelegate.InsertLichLamViec(objNguoiChuanBi);
            }
            DBLichLamViec.SubmitChanges();
        }

        public bool Delete(int IDLich)
        {
            LichLamViec obj = DBLichLamViec.LichLamViecs.SingleOrDefault(p => p.ID == IDLich);
            DBLichLamViec.LichLamViecShareds.DeleteAllOnSubmit(obj.LichLamViecShareds);
            DBLichLamViec.LichLamViec_NguoiChuanBis.DeleteAllOnSubmit(obj.LichLamViec_NguoiChuanBis);
            DBLichLamViec.LichLamViecs.DeleteOnSubmit(obj);
            DBLichLamViec.SubmitChanges();
            return true;
        }

        public List<LichLamViec> GetAllLichLamViecTheoEventDate(DateTime BeginDate, DateTime EndDate, bool Status)
        {
            BeginDate = CommonDelegate.FixDate(BeginDate, 1);
            EndDate = CommonDelegate.FixDate(EndDate, 2);
            //var lichlamviec = from llv in DBLichLamViec.LichLamViecs
            //                  where llv.EventDate >= BeginDate
            //                  && llv.EventDate <= EndDate
            //                  && llv.Status == Status
            //                  select llv;
            var lichlamviec = from llv in DBLichLamViec.LichLamViecs
                              where
                              llv.StartTime >= BeginDate
                              && llv.StartTime <= EndDate
                              && 
                              llv.Status == Status
                              select llv;
            return lichlamviec.ToList();
        }
        public List<LichLamViec> GetAllLichLamViecTheoEventDateChuaDuyet(DateTime BeginDate, DateTime EndDate, bool Status)
        {
            BeginDate = CommonDelegate.FixDate(BeginDate, 1);
            EndDate = CommonDelegate.FixDate(EndDate, 2);
            //var lichlamviec = from llv in DBLichLamViec.LichLamViecs
            //                  where llv.EventDate >= BeginDate
            //                  && llv.EventDate <= EndDate
            //                  && llv.Status == Status
            //                  select llv;
            var lichlamviec = from llv in DBLichLamViec.LichLamViecs
                              where
                                  //llv.StartTime >= BeginDate
                                  //&& llv.StartTime <= EndDate
                                  //&& 
                              llv.Status == false
                              select llv;
            return lichlamviec.ToList();
        }
        public PagedList<LichLamViec> GetAllLichLamViecTheoEventDate_PagedList(int? id, DateTime BeginDate, DateTime EndDate)
        {
            //return DBLichLamViec.LichLamViecs.Where(p => p.EventDate >= BeginDate
            //    && p.EventDate <= EndDate && p.NguoiTao == Convert.ToInt32(HttpContext.Current.Session["USERID"])).ToPagedList(id ?? 1, CommonVariables.PaggedItemsPerPage);
            BeginDate=CommonDelegate.FixDate(BeginDate, 1);
            var Enddate = CommonDelegate.FixDate(BeginDate, 2);
            return DBLichLamViec.LichLamViecs.Where(p => p.StartTime >= BeginDate && p.StartTime<=Enddate
                && p.NguoiTao == Convert.ToInt32(HttpContext.Current.Session["USERID"])).ToPagedList(id ?? 1, CommonVariables.PaggedItemsPerPage);
        }

        public LichLamViec BuildLichLamViecObject(LichLamViecForm form)
        {
            LichLamViec obj = new LichLamViec();
            obj.DiaDiem = form.DiaDiem;
            obj.DonViChuTri = form.DonViChuTri;
            //obj.EndTime = CommonDelegate.ConverToTime(form.EndTimeHH, form.EndTimeMM);
            //obj.EventDate = CommonDelegate.ConvertToDateTine(form.EventDate);
            //obj.StartTime = CommonDelegate.ConverToTime(form.StartTimeHH, form.StartTimeMM);
            obj.StartTime = CommonDelegate.ConvertTime(form.EventDate, form.StartTimeHH + ":" + form.StartTimeMM);
            obj.EndTime = CommonDelegate.ConvertTime(form.EndDate, form.EndTimeHH + ":" + form.EndTimeMM);
            obj.GhiChu = form.GhiChu;
            obj.KhachMoi = form.KhachMoi;
            //if (form.NguoiChuanBi != null && form.NguoiChuanBi.Value > 0)
            //    obj.NguoiChuanBi = form.NguoiChuanBi;
            //else obj.NguoiChuanBi = null;
            obj.NoiDung = form.NoiDung;
            obj.NguoiTao = Convert.ToInt32(HttpContext.Current.Session["USERID"]);
            obj.NgayTao = DateTime.Now;
            return obj;
        }

        public LichLamViecForm BuildLichLamViecForm(LichLamViec obj)
        {
            LichLamViecForm form = new LichLamViecForm();
            form.ID = obj.ID;
            form.DiaDiem = obj.DiaDiem;
            form.DonViChuTri = obj.DonViChuTri;
            form.EndTimeHH = obj.EndTime != null ? obj.EndTime.Value.ToString("HH") : "";
            form.EndTimeMM = obj.EndTime != null ? obj.EndTime.Value.ToString("mm") : "";

            form.EventDate = obj.StartTime != null ? obj.StartTime.Value.ToString("dd/MM/yyyy") : "";
            //form.EndDate = obj.EventDate != null ? obj.EventDate.Value.ToString("dd/MM/yyyy") : "";
            //form.EventDate = obj.StartTime != null ? obj.StartTime.Value.ToString("dd/MM/yyyy") : "";
            form.EndDate = obj.EndTime != null ? obj.EndTime.Value.ToString("dd/MM/yyyy") : "";
            
            form.GhiChu = obj.GhiChu;
            form.KhachMoi = obj.KhachMoi;
            form.NoiDung = obj.NoiDung;
            form.StartTimeHH = obj.StartTime != null ? obj.StartTime.Value.ToString("HH") : "";
            form.StartTimeMM = obj.StartTime != null ? obj.StartTime.Value.ToString("mm") : "";
            form.NguoiTao = obj.NguoiTao;
            form.NgayTao = obj.NgayTao;
            form.Status = obj.Status;
            foreach (LichLamViecShared item in obj.LichLamViecShareds)
            {
                form.InListIdThanhPhan += item.IdUser + ",";
                form.InListTextThanhPhan += (new CommonDelegate.CommonDelegate()).GetDisplayNameByUserId(item.IdUser.Value.ToString()) + ", ";
            }
            foreach (LichLamViec_NguoiChuanBi item in obj.LichLamViec_NguoiChuanBis)
            {
                form.InListIdNguoiChuanBi += item.IdUser + ",";
                form.InListTextNguoiChuanBi += (new CommonDelegate.CommonDelegate()).GetDisplayNameByUserId(item.IdUser.ToString()) + ", ";
            }
            return form;
        }

        public SelectList GetSelectListForComboboxLoai()
        {
            IList<object> selectList = new List<object>();
            selectList.Add(new { value = "1", Text = "Lịch cơ quan", SelectedValue = "1" });
            return new SelectList(selectList, "Value", "Text", 1);
        }

        public LichLamViec GetLichLamViecById(int id)
        {
            return DBLichLamViec.LichLamViecs.SingleOrDefault(p => p.ID == id);
        }

        public LichLamViec GetLichLamViecIdMax()
        {
            if (DBLichLamViec.LichLamViecs.Count() > 0)
                return DBLichLamViec.LichLamViecs.OrderByDescending(p => p.ID).ToList().ElementAtOrDefault(0);
            else return new LichLamViec();
        }

        public bool DuyetLich(string ListIdLich, bool duyet)
        {
            if (!string.IsNullOrEmpty(ListIdLich))
            {
                string[] arr = ListIdLich.Split(',');
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    QLPKWeb.Models.LinQ.LichLamViec.LichLamViec obj = this.GetLichLamViecById(int.Parse(arr[i].Trim()));
                    obj.Status = duyet;
                    DBLichLamViec.SubmitChanges();
                }
            }
            return true;
        }

        public List<LichLamViec> GetLichLamViecTheoUser(int IdUser, DateTime BeginDate, DateTime EndDate)
        {
            BeginDate = CommonDelegate.FixDate(BeginDate, 1);
            EndDate = CommonDelegate.FixDate(EndDate, 2);
            //var lichlamviec = from llv in DBLichLamViec.LichLamViecs
            //                  join tp in DBLichLamViec.LichLamViecShareds on llv.ID equals tp.IDLich
            //                  into a
            //                  from tp in a.DefaultIfEmpty()
            //                  where llv.EventDate >= BeginDate 
            //                  && llv.EventDate <= EndDate 
            //                  && llv.Status == true && tp.IdUser == IdUser
            //                  select llv;
            var lichlamviec = from llv in DBLichLamViec.LichLamViecs
                              join tp in DBLichLamViec.LichLamViecShareds on llv.ID equals tp.IDLich
                              into a
                              from tp in a.DefaultIfEmpty()
                              where llv.StartTime >= BeginDate
                              && llv.StartTime <= EndDate
                              && llv.Status == true && tp.IdUser == IdUser
                              select llv;
            return lichlamviec.ToList();
            //return DBLichLamViec.LichLamViecs.Where(p => p.EventDate >= BeginDate && p.EventDate <= EndDate && p.Status == true && p).ToList();
        }

        public List<LichLamViec> GetLichLamViecTheoIdPhong(int IdPhong, DateTime BeginDate, DateTime EndDate)
        {
            List<TB_User> listUser = DBCommon.TB_Users.Where(p => p.Department == IdPhong && p.IsActive == true && p.IsDelete == false).ToList();
            List<LichLamViec> listLich = new List<LichLamViec>();
            foreach (TB_User item in listUser)
            {
                List<LichLamViec> list = this.GetLichLamViecTheoUser(item.ID, BeginDate, EndDate);
                foreach (LichLamViec lich in list)
                {
                    listLich.Add(lich);
                }
            }
            return listLich;
        }

        public string CheckDayIsInListLichLamViec(int DayOfWeek, int IdUser, List<LichLamViec> ListLichDaDuyet)
        {
            string display = "";
            foreach (LichLamViec item in ListLichDaDuyet)
            {
                //DateTime eventdate = item.EventDate != null ? item.EventDate.Value : DateTime.Now;
                DateTime eventdate = item.StartTime != null ? item.EndTime.Value : DateTime.Now;
                int day = (int)eventdate.DayOfWeek;
                if (day == DayOfWeek && CheckUserInlist(item.LichLamViecShareds.ToList(), IdUser))
                    display += "<a style='cursor: pointer;color: blue; ' onclick=\"javascript:window.location.href = basePath + 'LichLamViec/XemLichLamViec/" + item.ID + "'\"> - "
                        + item.NoiDung + "</a><br />";
            }
            return display;
        }
        public List<string[]> BuildListStringListLichCongViec(List<TB_User> ListUser, DateTime FromDate, DateTime ToDate, int type)
        {
            List<string[]> listData = new List<string[]>();
            int stt = 0;
            foreach (QLPKWeb.Models.LinQ.Common.TB_User item in ListUser)
            {
                stt++;
                List<LichLamViec> ListLich = this.GetLichLamViecTheoUser(item.ID, FromDate, ToDate);
                string[] arr = new string[9];
                arr[0] = ((string.IsNullOrEmpty(item.LastName) || string.IsNullOrEmpty(item.FirstName))
                          ? item.UserName
                          : item.LastName + " " + item.FirstName);
                if (ListLich != null)
                {
                    for (int i = 1; i < 7; i++)
                    {
                        arr[i] = this.CheckDayIsInListLichLamViec(i, item.ID, ListLich);
                    }
                }
                else 
                    for (int i = 1; i < 7; i++)
                    {
                        arr[i] = "";
                    }

                TB_Department objdep = item.Department != null ? CommonDelegate.GetDepartmentByDepartmentId(item.Department.ToString()) : null;
                TB_JobTitle objJob = item.JobTitle != null ? CommonDelegate.GetJobTitleByJobTitleId(item.JobTitle.Value.ToString()) : null;
                arr[7] = type == 0 ? (objdep != null ? objdep.DepartmentName : "") : (objJob != null ? objJob.JobTitle : "");
                arr[8] = stt.ToString();
                listData.Add(arr);
            }
            return listData;
        }

        public bool CheckUserInlist(List<LichLamViecShared> ListThanhPhan, int IdUser)
        {
            foreach (LichLamViecShared item in ListThanhPhan)
            {
                if (item.IdUser == IdUser) return true;
            }
            return false;
        }

        //Build lịch sở
        public string BuildDataLichSo(DateTime FromDate, DateTime ToDate)
        {
            string build = "";
            List<LichLamViec> ListLichDaDuyet = this.GetAllLichLamViecTheoEventDate(FromDate, ToDate, true);
            for (int i = 1; i < 7; i++)
            {
                
                List<LichLamViec> listLich = ListLichDaDuyet
                                   .Where(p => (int)p.StartTime.Value.DayOfWeek == i).ToList();
                build += "<tr>"
                       + "     <td style='padding-left:3px;border: 1px solid #ddd' align='center' nowrap='nowrap' width='35px'>"
                       + "         No " + (i + 1).ToString()
                       + "     </td>"
                       + "     <td style='padding-left:3px;border: 1px solid #ddd' align='left' nowrap='nowrap' width='260px'>";
                foreach (LichLamViec item in listLich)
                {
                    //build += (item.StartTime != null ? item.StartTime.Value.ToString("HH:mm") : "")
                    //               + "<span> - </span>"
                    //               + (item.EndTime != null ? item.EndTime.Value.ToString("HH:mm") : "")
                    //               + "<br />";
                    build += (item.StartTime != null ? "- " + "<b>" + item.StartTime.Value.ToString("HH:mm") + "</b> Date <b>" + item.StartTime.Value.ToString("dd/MM/yyyy") + "</b>" : "")
                                   + "<span> - </span>"
                                   + (item.EndTime != null ? "<b>" + item.EndTime.Value.ToString("HH:mm") + "</b> Date <b>" + item.EndTime.Value.ToString("dd/MM/yyyy") + "</b>" : "")
                                   + "<br />";
                }
                build += "</td>"
                       + "     <td style='color: blue;cursor: pointer;padding-left:3px;border: 1px solid #ddd' align='left' nowrap='nowrap'>";
                foreach (LichLamViec item in listLich)
                {
                    build += "<span> - </span>"
                           + "        <a style='color: blue; cursor: pointer' title='" + item.NoiDung + "' onclick='javascript:XemLich(" + item.ID + ")' >"
                           + ConvertUtils.TruncateAtWord(item.NoiDung, 75)
                           + "        </a>"
                           + "        <br />";
                }
                build += "</td>"
                       + "     <td style='padding-left:3px;border: 1px solid #ddd' align='left'  nowrap='nowrap'>";
                foreach (LichLamViec item in listLich)
                {
                    build += "<span> - </span>"
                                   + this.GetDisplayNameOfThanhPhan(item.LichLamViecShareds.ToList(), 2)
                                   + "<br />";
                }
                build += "</td></tr>";
            }
            return build;
        }

        public string GetDisplayNameOfThanhPhan(List<LichLamViecShared> ListThanhPhan, int songuoi)
        {
            string display = "";
            if (ListThanhPhan.Count < songuoi)
            {
                foreach (LichLamViecShared item in ListThanhPhan)
                {
                    display += CommonDelegate.GetDisplayNameByUserId(item.IdUser.Value.ToString()) + ", ";
                }
                display = display.Substring(0, display.Length - 2);
            }
            else
            {
                for (int i = 0; i < songuoi; i++)
                {
                    display += CommonDelegate.GetDisplayNameByUserId(ListThanhPhan[i].IdUser.Value.ToString()) + ", ";
                }
                display = display.Substring(0, display.Length - 2);
                display += " <a  style='color: blue;cursor: pointer'id='XemThanhPhan" + ListThanhPhan[0].IDLich + "' class='XemThanhPhan' onclick='javascript:XemChiTietThanhPhan(" + ListThanhPhan[0].IDLich + ")'> Views</a>";
            }
            return display;
        }
    }
}